package com.macro.mall.tiny.modules.pms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.modules.pms.model.PmsBrand;
import com.macro.mall.tiny.modules.pms.model.PmsCategory;
import com.macro.mall.tiny.modules.pms.model.PmsErrorCode;
import com.macro.mall.tiny.modules.pms.service.PmsBrandService;
import com.macro.mall.tiny.modules.pms.service.PmsCategoryService;
import com.macro.mall.tiny.modules.pms.service.PmsErrorCodeService;
import com.macro.mall.tiny.modules.pms.service.PmsUserActionService;
import com.macro.mall.tiny.security.util.CharUtil;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/pms/pmsErrorCode")
@Api(tags = "PmsErrorCodeController")
@Tag(name = "PmsErrorCodeController", description = "错误码管理")
public class PmsErrorCodeController {

    @Autowired
    private PmsErrorCodeService pmsErrorCodeService;

    @Autowired
    private PmsCategoryService pmsCategoryService;

    @Autowired
    private PmsBrandService pmsBrandService;


    @ApiOperation("根据品牌ID获取错误码分类")
    @GetMapping("/getErrorCodeCategoryByBrandId")
    public CommonResult<List<Map<String, Object>>> getErrorCodeCategoryByBrandId(@RequestParam Integer brandId) {
        List<Map<String, Object>> result = pmsErrorCodeService.getErrorCodeCategoryByBrandId(brandId);
        return CommonResult.success(result);
    }

    @ApiOperation("获取具体错误码")
    @GetMapping("/getDetailErrorCode")
    public CommonResult<List<PmsErrorCodeVO>> getDetailErrorCode(@RequestParam Integer brandId, @RequestParam Integer categoryId) {
        List<PmsErrorCode> list = pmsErrorCodeService.list(new QueryWrapper<PmsErrorCode>()
                .select("error_code")
                .eq("brand_id", brandId)
                .eq("category_id", categoryId).groupBy("error_code"));
        if (ObjectUtils.isEmpty(list)) {
            return CommonResult.success(new ArrayList<>());
        }
        Map<String, Long> frequencyMap = list.stream()
                .collect(Collectors.groupingBy(PmsErrorCode::getErrorCode, Collectors.counting()));

        List<String> top12ErrorCodes = frequencyMap.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .limit(12)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        List<String> collect = list.stream().map(PmsErrorCode::getErrorCode).collect(Collectors.toList());
        List<PmsErrorCodeVO> result = new ArrayList<>();
        for (String s : collect) {
            PmsErrorCodeVO pmsErrorCodeVO = new PmsErrorCodeVO();
            pmsErrorCodeVO.setErrorCode(s);
            pmsErrorCodeVO.setFirstLetter(CharUtil.getFirstLetter(s));
            pmsErrorCodeVO.setShowStatus(top12ErrorCodes.contains(s) ? 1 : 0);
            result.add(pmsErrorCodeVO);
        }
        return CommonResult.success(result);
    }

    @ApiOperation("获取错误码详情")
    @GetMapping
    public CommonResult<List<PmsErrorCode>> getErrorCodeDetailList(@RequestParam Integer brandId,
                                                                   @RequestParam Integer categoryId,
                                                                   @RequestParam String errorCode) {
        if (MemberContext.getMember() == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        if (MemberContext.getMember().getVip() == null || MemberContext.getMember().getVip().equals(0)) {
            return CommonResult.failed(ResultCode.NEED_VIP);
        }
        List<PmsErrorCode> result = pmsErrorCodeService.list(new QueryWrapper<PmsErrorCode>()
                .eq("brand_id", brandId)
                .eq("category_id", categoryId)
                .eq("error_code", errorCode));
        handlePrivacyData(result);
        return CommonResult.success(result);
    }


    @ApiOperation("分页获取获取错误码列表(万能接口) 支持id、brandId,errorCode、adaptType,categoryId、content、title ")
    @PostMapping("page")
    public CommonResult<IPage<PmsErrorCode>> listErrorCode(@RequestBody PmsErrorCode pmsErrorCode
            , @ApiParam(defaultValue = "1") @RequestParam Integer pageNum,@ApiParam(defaultValue = "10") @RequestParam Integer pageSize) {
        if (pageNum == null) pageNum = 1;
        if (pageSize == null)  pageSize = 10;

        QueryWrapper<PmsErrorCode> query = new QueryWrapper<>();

        if (pmsErrorCode.getId() != null)query.eq("id", pmsErrorCode.getId());
        if (pmsErrorCode.getBrandId() != null) query.eq("brand_id", pmsErrorCode.getBrandId());
        if (pmsErrorCode.getCategoryId() != null) query.eq("category_id", pmsErrorCode.getCategoryId());
        if (pmsErrorCode.getErrorCode() != null) query.eq("error_code", pmsErrorCode.getErrorCode());
        if (StringUtils.isNotEmpty(pmsErrorCode.getAdaptType())) query.like("adapt_type", pmsErrorCode.getAdaptType());
        if (StringUtils.isNotEmpty(pmsErrorCode.getTitle())) query.like("title", pmsErrorCode.getTitle());
        if (StringUtils.isNotEmpty(pmsErrorCode.getContent())) query.like("content", pmsErrorCode.getContent());

        IPage<PmsErrorCode> result = pmsErrorCodeService.page(new Page<>(pageNum, pageSize, true), query);
        if (!result.getRecords().isEmpty()) {
            Map<Integer, PmsCategory> collect = pmsCategoryService.list().stream().collect(Collectors.toMap(PmsCategory::getId, category -> category));
            Map<Integer, PmsBrand> brandMap = pmsBrandService.list().stream().collect(Collectors.toMap(PmsBrand::getId, item -> item));

            result.getRecords().forEach(e -> {
                if (collect.get(e.getCategoryId()) != null) {
                    e.setCategoryName(collect.get(e.getCategoryId()).getName());
                }
                if (brandMap.get(e.getBrandId()) != null) {
                    e.setBrandName(brandMap.get(e.getBrandId()).getName());
                }
            });
        }
        handlePrivacyData(result.getRecords());
        return CommonResult.success(result);
    }

    @ApiOperation("后台添加错误码")
    @PostMapping("/add")
    public CommonResult<Void> addErrorCode(@RequestBody PmsErrorCode pmsErrorCode) {
        pmsErrorCodeService.save(pmsErrorCode);
        return CommonResult.success(null);
    }

    @ApiOperation("后台修改错误码")
    @PutMapping("/update")
    public CommonResult<Void> updateErrorCode(@RequestBody PmsErrorCode pmsErrorCode) {
        pmsErrorCodeService.updateById(pmsErrorCode);
        return CommonResult.success(null);
    }

    @ApiOperation("后台批量删除错误码")
    @DeleteMapping("/delete")
    public CommonResult<Void> deleteErrorCode(@RequestParam("ids") List<Integer> ids) {
        pmsErrorCodeService.removeByIds(ids);
        return CommonResult.success(null);
    }

    @Autowired
    private PmsUserActionService pmsUserActionService;

    private void handlePrivacyData(List<PmsErrorCode> lists) {
        if (MemberContext.getMember()!=null) {
            List<Object> objects = pmsUserActionService.listItem(0,0);
            for (PmsErrorCode errorCase : lists) {
                if (objects.contains(errorCase.getId())) {
                    errorCase.setCurrentMemberLike(1);
                }else {
                    errorCase.setCurrentMemberLike(0);
                }
            }
        }
    }

    @Data
    class PmsErrorCodeVO {
        @ApiModelProperty(value = "错误码")
        private String errorCode;

        @ApiModelProperty(value = "首字母")
        private String firstLetter;

        @ApiModelProperty(value = "展示状态 0:普通 1:热门 默认为普通")
        private Integer showStatus;
    }
}

